const Answers = require("../db/model/answers")
const User = require("../db/model/users")
const { SuccessModel, ErrorModel } = require("../utils/resModel")

class AnswersCtl {
    /**
     * 获取话题列表
     * @param {*} ctx 
     */
    async find(ctx) {
        const { per_page = 10 } = ctx.query
        const perPage = Math.max(parseInt(per_page), 1)
        const page = Math.max(parseInt(ctx.query.page), 1) - 1
        const q = new RegExp(ctx.query.q)
        const list = await Answers
            .find({ content: q, questionId: ctx.params.questionId })
            .limit(perPage).skip(page * perPage)
            .populate("answerer")
        ctx.body = new SuccessModel(list)
    }

    /**
     * 根据id查询一个话题
     * @param {*} ctx 
     */
    async findById(ctx) {
        const { fields = "" } = ctx.query
        let selectFields = fields.split(";").filter(f => f).map(f => ' +' + f).join(" ")
        const answer = await Answers.findById(ctx.params.id).select(selectFields).populate("answerer")
        ctx.body = new SuccessModel(answer)
    }

    /**
     * 检查该问题是否属于该用户
     * @param {*} ctx 
     * @param {*} next 
     */
    async checkAnswerser(ctx, next) {
        const { answer } = ctx.state
        if (answer.answerer.toString() !== ctx.state.user._id) {
            ctx.throw(403, "没有权限操作")
        }
        await next()
    }

    /**
     * 查询话题是否存在
     * @param {*} ctx 
     * @param {*} next 
     */
    async checkAnswersExist(ctx, next) {
        const answer = await Answers.findById(ctx.params.id).select("+answerer")
        if (!answer) {
            ctx.throw(404, "回答不存在")
        }
        // 只有删改查答案的时候才检查此逻辑，赞和踩答案的时候不检查此逻辑
        if (ctx.params.questionId && answer.questionId !== ctx.params.questionId) {
            ctx.throw(404, "该问题下没有此回答")
        }
        ctx.state.answer = answer
        await next()
    }

    /**
     * 创建一个问题
     * @param {*} ctx 
     */
    async create(ctx) {
        ctx.verifyParams({
            content: { type: "string", required: true }
        })
        const answerer = ctx.state.user._id
        const { questionId } = ctx.params
        console.log(questionId)
        const answer = await new Answers({ ...ctx.request.body, answerer, questionId }).save()
        ctx.body = new SuccessModel(answer)
    }

    /**
     * 修改一个问题
     * @param {*} ctx 
     */
    async update(ctx) {
        ctx.verifyParams({
            content: { type: "string", required: false }
        })
        const answer = await ctx.state.answer.update(ctx.request.body)
        ctx.body = new SuccessModel(answer)
    }

    /**
     * 删除一个问题
     * @param {*} ctx 
     */
    async deleteAnswers(ctx) {
        const answer = await Answers.findByIdAndRemove(ctx.params.id)
        ctx.body = new SuccessModel(answer)
    }

}



module.exports = new AnswersCtl()